//
//  JsonUtil.swift
//  Swift-Codedase
//
//  Created by 徐先生 on 2023/2/27.
//
//  https://www.mianshigee.com/project/HandyJSON


import UIKit
import HandyJSON

class JsonUtil: NSObject {
    
    /// JsonString 转 Model
    /// - Parameters:
    ///   - string: Json字符串
    ///   - modelType: model 类型
    /// - Returns: 返 model 对象
    static func modelFromJsonString<T: HandyJSON>(_ string: String, _ modelType: T.Type) -> T? {
        if string == "" || string.count == 0 {
#if DEBUG
            xLog("jsonoModel: 字符串为空")
#endif
            return nil
        }
        return T.deserialize(from: string)
    }
    
    
    /// Array 转 Models
    /// - Parameters:
    ///   - array: Array
    ///   - modelType: model 类型
    /// - Returns: Models 数组
    static func modelsFromArray<T: HandyJSON>(_ array: [Any], _ modelType: T.Type) -> [T] {
        if array.count == 0 {
#if DEBUG
            xLog("jsonoModel: 字符串为空")
#endif
            return []
        }
        
        guard let result = [T].deserialize(from: array) else {
            return []
        }
        // 从数组中删除所有’nil’元素。
        return result.compactMap{ $0 }
    }
    
    
    /// JsonString 转 Models
    /// - Parameters:
    ///   - string: JsonString
    ///   - modelType: model 类型
    /// - Returns: 返 model 对象数组
    static func modelFromJsonArrayString<T: HandyJSON>(_ string: String, _ modelType: T.Type) -> [T] {
        if string == "" || string.count == 0 {
#if DEBUG
            xLog("jsonToModelArray: 字符串为空")
#endif
            return []
        }
        
        guard let result = [T].deserialize(from: string) else {
            return []
        }
        // 从数组中删除所有’nil’元素。
        return result.compactMap{ $0 }
    }
    
    /// Dictionary 转 Model
    /// - Parameters:
    ///   - string: Dictionary
    ///   - modelType: model 类型
    /// - Returns: 返 model 对象
    static func modelFromDictionary<T: HandyJSON>(_ string: [String: Any], _ modelType: T.Type) -> T? {
        if string.count == 0 {
#if DEBUG
            xLog("dictionaryToModel:字符串为空")
#endif
            return nil
        }
        return modelType.deserialize(from: string)
    }
    
    
    /// Model 转 JsonString
    /// - Parameter model: model 对象
    /// - Returns: 返回 JsonString
    static func jsonStringFromModel<T: HandyJSON>(_ model: T?) -> String {
        if model == nil {
#if DEBUG
            xLog("modelToJson:model为空")
#endif
            return ""
        }
        return (model?.toJSONString())!
    }
    
    /// Model 转 Dictionary
    /// - Parameter model: model 对象
    /// - Returns: Dictionary
    static func dictionaryFromModel<T: HandyJSON>(_ model: T?) -> [String: Any] {
        if model == nil {
#if DEBUG
            xLog("modelToJson:model为空")
#endif
            return [:]
        }
        return (model?.toJSON())!
    }
    
    
    /// JsonString 转 Dictionary
    /// - Parameter jsonString: jsonString 字符串
    /// - Returns: 返 Dictionary
    static func dictionaryFromJsonString(_ string: String) -> [String: Any]{
        
        let jsonData: Data = string.data(using: .utf8)!
        
        let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
        if dict != nil {
            return dict as! [String: Any]
        }
        return [:]
    }
    
    /// JsonString 转 Array
    /// - Parameter string: jsonString
    /// - Returns: 返 数组
    static func arrayFromJsonString(_ string: String) -> [Any]{
        
        let jsonData: Data = string.data(using: .utf8)!
        
        let array = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
        if array != nil {
            return array as! [Any]
        }
        return []
    }
    
    /// Dictionary 转 JsonString
    /// - Parameter dictionary: 字典
    /// - Returns: 返 JsonString
    static func jsonStringFromDictionary(_ dictionary: [String: Any]) -> String {
        if (!JSONSerialization.isValidJSONObject(dictionary)) {
            xLog("无法解析出JSONString")
            return ""
        }
        let data : NSData! = try? JSONSerialization.data(withJSONObject: dictionary, options: []) as NSData?
        let JSONString = NSString(data:data as Data, encoding: String.Encoding.utf8.rawValue)
        return JSONString! as String
    }
    
    
    /// Array 转 JsonString
    /// - Parameter array: Array
    /// - Returns: 返 JsonString
    static func jsonStringFromArray(_ array: [Any]) -> String {
        
        if (!JSONSerialization.isValidJSONObject(array)) {
            xLog("无法解析出JSONString")
            return ""
        }
        let data : NSData! = try? JSONSerialization.data(withJSONObject: array, options: []) as NSData?
        let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
        return JSONString! as String
    }
}
